/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package service;

import entity.Article;
import entity.Image;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
/**
 *
 * @author Gael
 */
@Stateless
@Path("/articles")
public class ArticleFacadeREST extends AbstractFacade<Article> {
    @EJB
    private ImageFacadeREST imageFacadeREST;
    @PersistenceContext(unitName = "BlogDPU")
    private EntityManager em;
    private  String FILE_UPLOAD_PATH = "C:/Users/Gael/Documents/NetBeansProjects/BlogD/web/img";
    public ArticleFacadeREST() {
        super(Article.class);
    }
    
    @POST
    @Path("/ajoutfull")
    @Consumes({MediaType.MULTIPART_FORM_DATA})
    public String AjoutArticleFull(@Context HttpServletRequest request) {
        String responseStatus = "Successful";   
        
        if (ServletFileUpload.isMultipartContent(request)){
            final FileItemFactory factory = new DiskFileItemFactory();
            final ServletFileUpload fileUpload = new ServletFileUpload(factory);
            Article a = new Article();
            
            try{
                final List items = fileUpload.parseRequest(request);
                if (items != null)
                {
                    final Iterator iter = items.iterator();
                    while (iter.hasNext())
                    {
                        final FileItem item = (FileItem) iter.next();
                        final String itemName = item.getName();
                        final String fieldName = item.getFieldName(); 
                        final String fieldValue = item.getString();
                        System.err.println("=====DEBUT=======================================================");
                        if (item.isFormField())
                        {
//                            candidateName = fieldValue;
                            System.out.println("Field Name: " + fieldName + ", Field Value: " + fieldValue);
//                            System.out.println("Candidate Name: " + candidateName);
                            if(fieldName.equals("titre")){
                                a.setTitre(fieldValue);
                            }
                            if(fieldName.equals("contenu")){
                                a.setContenu(fieldValue);
                            }
                            
                        }
                        else
                        {
                                Image i = new Image();
                                imageFacadeREST.create(i);
                                
                                
                                
                                final File savedFile = new File(FILE_UPLOAD_PATH + File.separator
                                         + fieldName + i.getId()+".jpg");
                                System.out.println("========================Saving the file: " + savedFile.getName());
                                try{
                                    
                                   item.write(savedFile);   
                                   i.setChemin("img/"+fieldName+i.getId()+".jpg");
                                   i.setNom(savedFile.getName());
                                   imageFacadeREST.edit(i);
                                   System.out.println(i.toString());
                                   a.addImage(i);
                                }catch(Exception e){
                                    imageFacadeREST.remove(i);
                                    System.err.print("++++++++++ echec d'écriture pour"+savedFile.getName());
                                    responseStatus ="Failed";
                                }
                                                            
                        }
                         System.err.println("=====FIN=======================================================");
                        

                    }
                }
            }catch(FileUploadException fue){
                System.err.print("++++++++++ echec multi pack");
                fue.printStackTrace(); 
                responseStatus ="Failed";
            }
            super.create(a);
            responseStatus ="/BlogD/resources/articles/"+a.getId();
//           responseStatus = a.getId().toString()+"=$*"+a.getTitre()+"=$*"+a.getContenu()+"=$*"+a.getLink();
        }
        return   responseStatus;     
    }
    
    @GET
    @Path("/init")
    @Consumes({"application/xml", "application/json"})
    public String createInit() {
        Article a = new Article("article 1", " Blablablablablablabla");
        super.create(a);
        
        Article a2 = new Article("article 2", " Blablablablablablabla");
        super.create(a2);
        Article a3 = new Article("article 3", " Blablablablablablabla");
        super.create(a3);

       
        return "ok";        
    }

    @POST
    @Override
    @Consumes({"application/xml", "application/json"})
    public void create(Article entity) {
        super.create(entity);
    }

    @PUT
    @Override
    @Consumes({"application/xml", "application/json"})
    public void edit(Article entity) {
        super.edit(entity);
    }

    @DELETE
    @Path("{id}")
    public void remove(@PathParam("id") Long id) {
        super.remove(super.find(id));
    }

    @GET
    @Path("{id}")
    @Produces({"application/xml", "application/json"})
    public Article find(@PathParam("id") Long id) {
        return super.find(id);
    }

    @GET
    @Override
    @Produces({"application/xml", "application/json"})
    public List<Article> findAll() {
        return super.findAll();
    }

    @GET
    @Path("{from}/{to}")
    @Produces({"application/xml", "application/json"})
    public List<Article> findRange(@PathParam("from") Integer from, @PathParam("to") Integer to) {
        return super.findRange(new int[]{from, to});
    }

    @GET
    @Path("count")
    @Produces("text/plain")
    public String countREST() {
        return String.valueOf(super.count());
    }

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }
    
}
